//
//  OauthController.m
//  CMJWeibo
//
//  Created by BH on 15/12/11.
//
//

#import "OauthController.h"
#import "Account.h"
#import "AccountTool.h"
#import "ChangeController.h"
#import <MBProgressHUD/MBProgressHUD.h>
#import "CMJCommon.h"
#import "AccessTokenParam.h"

@interface OauthController ()<UIWebViewDelegate>
{
    MBProgressHUD *hud;
}

@end

@implementation OauthController

-(void)viewDidLoad
{
    [super viewDidLoad];
    
    UIWebView *webView = [[UIWebView alloc] initWithFrame:self.view.bounds];
    webView.delegate = self;
    [self.view addSubview:webView];
    
    //加载登录授权页
    NSString *urlStr = [NSString stringWithFormat:@"https://api.weibo.com/oauth2/authorize?client_id=%@&redirect_uri=%@",Appkey,AppRedirectURI];
    NSURL *url = [NSURL URLWithString:urlStr];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    [webView loadRequest:request];
}

#pragma mark - webview delegate
-(void)webViewDidStartLoad:(UIWebView *)webView
{
    hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.labelText = @"正在加载中。。。";
    hud.dimBackground = YES;
    [hud show:YES];
}

-(void)webViewDidFinishLoad:(UIWebView *)webView
{
    [hud hide:YES];
    [hud removeFromSuperview];
}

/**
 *  webView每当发送一次请求之前, 都会先调用这个方法
 *
 *  @param request        这次发送的请求
 *
 *  @return YES : 允许加载这次请求, NO : 拒绝加载这次请求
 */
-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    // 获得这次请求的路径
    NSString *urlStr = request.URL.absoluteString;
    
    // 检测这个url是否为回调地址(包含了"code=")
    NSRange range = [urlStr rangeOfString:@"code="];
    if (range.location != NSNotFound) {
        // 找到了code=，截取code=后面的内容
        NSInteger fromIndex = range.location + range.length;
        NSString *code = [urlStr substringFromIndex:fromIndex];
        
        // 利用code(用户授权过的请求标记) 换取 一个 accessToken(访问标记)
        [self getAccessTokenWithCode:code];
        
        //禁止加载回调页
        return NO;
    }
    
    return YES;
}

/**
 *  利用code 换取 一个 accessToken(访问标记
 *
 *  @param code 用户授权过的请求标记
 */
-(void)getAccessTokenWithCode:(NSString *)string
{
    // 封装请求参数
    AccessTokenParam *param = [[AccessTokenParam alloc] init];
    param.client_id = Appkey;
    param.client_secret = Appsecret;
    param.grant_type = @"authorization_code";
    param.redirect_uri = AppRedirectURI;
    param.code = string;
    // 获得accessToken
    [AccountTool accessTokenWithParam:param success:^(AccessTokenResult *result) {
        // 归档模型
        [AccountTool saveAccount:result];
        // 切换控制器
        [ChangeController chooseRootViewController];
        
    } failure:^(NSError *error) {
        NSLog(@"%@",error.localizedDescription);
    }];
}

@end
